echo "**********************************"
echo "******* 1: 初始化脚本参数 *********"
echo "**********************************"

# docker映射到宿主机目录
DOCKER_MAPPING_HOST_PATH=/home/lorry/k8s/prometheus
PROME_HOME_PATH=/data/workspace/k8s_env/prometheus/install
mkdir -p $PROME_HOME_PATH
HOST_DN1=cn5
HOST_DN2=cn6
HOST_DN3=cn7
HOSTS=($HOST_DN1 $HOST_DN2 $HOST_DN3)
USER=lorry
NAME_SPACE=default
CONTAINER_IMAGE_PATH=bg9:8083/prom/prometheus:v2.31.1
SVC_NODE_PORT=30090
HOSTS_STR=

echo ""
echo "*********************************************"
echo "******* 2: 远程构建容器映射宿主机目录 *********"
echo "*********************************************"

# 遍历宿主机，创建映射目录
for dn in "${HOSTS[@]}"; do
    echo "dn: $dn"
    ssh $USER@${dn} "mkdir -p $DOCKER_MAPPING_HOST_PATH"
    HOST_STR=$HOST_STR$dn","
done
echo "HOST_STR: $HOST_STR"
echo ""
echo "*********************************************"
echo "******* 3: 构建yaml文件 *********"
echo "*********************************************"

cat << EOF > $PROME_HOME_PATH/prometheus-cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: prometheus-config
  namespace: $NAME_SPACE
data:
  prometheus.yml: |
    global:
      scrape_interval: 15s
      scrape_timeout: 15s
    scrape_configs:
    - job_name: 'prometheus'
      static_configs:
      - targets: ['localhost:9090']
EOF

cat << EOF > $PROME_HOME_PATH/prometheus-deploy.yaml
# prometheus-deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: prometheus
  namespace: $NAME_SPACE
  labels:
    app: prometheus
spec:
  selector:
    matchLabels:
      app: prometheus
  template:
    metadata:
      labels:
        app: prometheus
    spec:
      serviceAccountName: prometheus
      containers:
        - image: $CONTAINER_IMAGE_PATH
          name: prometheus
          args:
            - "--config.file=/etc/prometheus/prometheus.yml"
            - "--storage.tsdb.path=/prometheus" # 指定tsdb数据路径
            - "--storage.tsdb.retention.time=24h"
            - "--web.enable-admin-api" # 控制对admin HTTP API的访问，其中包括删除时间序列等功能
            - "--web.enable-lifecycle" # 支持热更新，直接执行localhost:9090/-/reload立即生效
            - "--web.external-url=/prome/" # 这是 Prometheus 外部可达的地址（URL）（经反向代理后）
            - "--web.route-prefix=/" # Prometheus 内部 Web 请求的路由前缀。
          ports:
            - containerPort: 9090
              name: http
          volumeMounts:
            - mountPath: "/etc/prometheus"
              name: config-volume
            - mountPath: "/prometheus"
              name: data
          resources:
            requests:
              cpu: 200m
              memory: 1024Mi
            limits:
              cpu: 200m
              memory: 1024Mi
      volumes:
        - name: data
          persistentVolumeClaim:
            claimName: prometheus-data
        - configMap:
            name: prometheus-config
          name: config-volume
      initContainers:
      - name: fix-permissions
        image: bg9:8083/busybox:latest
        command: [chown, -R, "nobody:nobody", /prometheus]
        volumeMounts:
        - name: data
          mountPath: /prometheus
EOF
cat << EOF > $PROME_HOME_PATH/prometheus-svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: prometheus
  namespace: $NAME_SPACE
  labels:
    app: prometheus
spec:
  selector:
    app: prometheus
  type: NodePort
  ports:
    - name: web
      port: 9090
      targetPort: http
      nodePort: $SVC_NODE_PORT
EOF

cat << EOF > $PROME_HOME_PATH/prometheus-pv.yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: local-storage
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer
---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: prometheus-local
  labels:
    app: prometheus
spec:
  accessModes:
    - ReadWriteOnce
  capacity:
    storage: 20Gi
  storageClassName: local-storage
  local:
    path: $DOCKER_MAPPING_HOST_PATH
  persistentVolumeReclaimPolicy: Retain
  nodeAffinity:
    required:
      nodeSelectorTerms:
        - matchExpressions:
            - key: kubernetes.io/hostname
              operator: In
              values: [$HOST_STR]
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: prometheus-data
  namespace: $NAME_SPACE
spec:
  selector:
    matchLabels:
      app: prometheus
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 20Gi
  storageClassName: local-storage
EOF

cat << EOF > $PROME_HOME_PATH/prometheus-rbac.yaml
# rbac.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: prometheus
  namespace: $NAME_SPACE
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: prometheus
rules:
  - apiGroups:
      - ""
    resources:
      - nodes
      - services
      - endpoints
      - pods
      - nodes/proxy
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - "extensions"
    resources:
      - ingresses
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - ""
    resources:
      - configmaps
      - nodes/metrics
    verbs:
      - get
  - nonResourceURLs:
      - /metrics
    verbs:
      - get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: prometheus
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: prometheus
subjects:
  - kind: ServiceAccount
    name: prometheus
    namespace: $NAME_SPACE
EOF

echo ""
echo "*********************************************"
echo "******* 4: 执行kubectl运行yaml文件 ***********"
echo "*********************************************"

# 强制删除(force无法删除的场景，使用下面方式)，其中“k8s-pv-kafka02”是容器的
# kubectl patch pv k8s-pv-kafka02 -p '{"metadata":{"finalizers":null}}'
kubectl delete -f $PROME_HOME_PATH --force --grace-period=0
kubectl apply -f $PROME_HOME_PATH 

echo ""
echo "*********************************************"
echo "******* 5: 获取pod状态 ***********"
echo "*********************************************"

sleep 2s
kubectl get pod -n $NAME_SPACE
sleep 3s
kubectl get pod -n $NAME_SPACE
